package code.cando;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * author : yeswater
 * date : 2023/12/5
 * 三数之和
 * 所有和为 0 且不重复的三元组
 */

public class T015 {
    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum(nums).toString());
    }

    // 自己的思路有问题  l r + m (这种方法l++ 和 r--的时机不好确定)
    public static List<List<Integer>> threeSum1(int[] nums) {
        int m = nums.length;
        int l = 0, r = m - 1;
        List<List<Integer>> res = new ArrayList<>();
        while (l < r) {
            for (int i = l + 1; i < r; i++) {
                System.out.println("l=" + l + " i=" + i + " r=" + r);
                int sum = nums[l] + nums[i] + nums[r];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[l], nums[i], nums[r]));
                    while (++i < r && nums[i] == nums[i-1]) i++;
                }
                else if (sum < 0) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return res;
    }

    /**
     * 前驱(向后走) + l + r
     * 出处: https://leetcode.cn/problems/3sum/solutions/12307/hua-jie-suan-fa-15-san-shu-zhi-he-by-guanpengchn/
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int len = nums.length;
        if (nums.length < 3) return ans;
        Arrays.sort(nums);
        for (int i = 0; i < len - 2; i++) {
            if (nums[i] > 0) {
                break; // 当前数字大于 0 则三数和肯定大于 0
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue; // 去重
            }
            int L = i + 1;
            int R = len - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    ans.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    // 结果去重
                    while (L < R && nums[L] == nums[L + 1]) L++;
                    while (L < R && nums[R] == nums[R - 1]) R--;
                    L++;
                    R--;
                } else if (sum > 0) {
                    R--;
                } else {
                    L++;
                }
            }
        }
        return ans;
    }
}
